package com.laycoding.layrpc.service;

import com.laycoding.layrpc.common.LayRpcRegistryCache;
import com.laycoding.layrpc.common.LayRpcRegistyCache;
import com.laycoding.layrpc.entity.LayRpcMessage;
import com.laycoding.layrpc.handler.client.LayRpcClientRegistry;
import com.laycoding.layrpc.handler.client.RpcProxyHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalTime;

@Slf4j
public class RpcServiceImpl implements RpcService{

    @Autowired
    LayRpcClientRegistry layRpcClientRegistry;

    private ThreadLocal<String> serviceUrl = new ThreadLocal<>();
    @Override
    @Retryable(value = Exception.class,backoff = @Backoff(delay = 1000,multiplier = 1.5))
    public Object sendMessage(LayRpcMessage message) throws Exception {
        Object res = layRpcClientRegistry.sendMessage(message);
        return  res;
    }
    @Recover
    public Object recover(Exception e){
        String url = serviceUrl.get();
        LayRpcRegistyCache.removeService(url);
        serviceUrl.remove();
        return e.getMessage();
    }
}
